package com.ld.security.common.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;


public class JsonUtil {

    private static final ObjectMapper mapper;

    static {
        mapper=new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String toJson(Object obj)  {

        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("对象转换异常:"+obj);
        }
    }

    @SneakyThrows
    private static <T> T toObject(byte[] json,Class<T> cla,Class<?>... clazz) {

        if(clazz.length == 0){
            return mapper.readValue(json,cla);
        }else{
            return mapper.readValue(json,getCollectionType(cla,clazz));
        }


    }
    public static <T> T toObject(String json,Class<T> cla,Class<?>... clazz) {

        try {
            return toObject(json.getBytes(),cla,clazz);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("字符串转换异常:"+json);
        }
    }

    public static <E> E toObject(String json, TypeReference<E> tr){
        E obj = JSON.parseObject(json, tr);
        return obj;
    }


    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }


}

